import ctypes
import logging
import platform
import sys

from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtGui import QIcon
from PyQt5.QtNetwork import QLocalSocket, QLocalServer
from PyQt5.QtWidgets import QMainWindow, QFileDialog

from aboutdialog import AboutDialog
from tools import tools
from tools.tools import basic_log_config, load_yaml
from configs.strings import combox, translate


class MainFrame(QMainWindow):
    def __init__(self):
        super(MainFrame, self).__init__()
        basic_log_config()
        self.config = load_yaml()
        self.lang = combox[self.config["APP"]["LANGUAGE"]]
        self.init_ui()
        self.init_args()
        self.init_slots()

    def init_ui(self):
        sys = platform.system()
        if sys == "Windows":
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                self.config["APP"]["APP_NAME"])

        self.centralwidget = QtWidgets.QWidget()
        self.centralwidget.setEnabled(True)
        self.setCentralWidget(self.centralwidget)

        self.mainLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.mainWidget = QtWidgets.QWidget()
        self.setGeometry(QtCore.QRect(0, 0, 1600, 900))
        self.setWindowTitle(self.config["APP"]["APP_NAME"])
        self.setWindowIcon(QIcon(self.config["APP"]["ICON"]))
        self.mainWidget.setLayout(self.mainLayout)
        self.setCentralWidget(self.mainWidget)

        # Menu UI
        self.menubar = self.menuBar()
        self.menuConfiguration = self.menubar.addMenu(translate['CONFIG'][self.lang])
        self.saveConfigAction = QtWidgets.QAction(translate['SAVE_CONFIG'][self.lang])
        self.loadConfigAction = QtWidgets.QAction(translate['LOAD_CONFIG'][self.lang])
        self.menuConfiguration.addAction(self.saveConfigAction)
        self.menuConfiguration.addAction(self.loadConfigAction)
        self.menubar.addAction(self.menuConfiguration.menuAction())

        self.menuHelp = self.menubar.addMenu(translate['HELP'][self.lang])
        self.aboutAction = QtWidgets.QAction(translate['ABOUT'][self.lang])
        self.menuHelp.addAction(self.aboutAction)
        self.menubar.addAction(self.menuHelp.menuAction())

        # Tool Button
        self.btnToolbar = QtWidgets.QHBoxLayout(self.centralwidget)
        configGroupBox = QtWidgets.QGroupBox("")
        configGroupBox.setLayout(self.btnToolbar)
        self.mainLayout.addWidget(configGroupBox, 0, 0, 1, 3)

        self.startBtn = QtWidgets.QToolButton()
        self.startBtn.setText(translate["START"][self.lang])
        self.startBtn.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.startBtn.setIcon(QtGui.QIcon(self.config["APP"]["START_COL_ICON"]))
        self.startBtn.setIconSize(QtCore.QSize(50, 50))

        self.stopBtn = QtWidgets.QToolButton()
        self.stopBtn.setText(translate["STOP"][self.lang])
        self.stopBtn.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.stopBtn.setIcon(QtGui.QIcon(self.config["APP"]["STOP_COL_ICON"]))
        self.stopBtn.setIconSize(QtCore.QSize(50, 50))

        self.btnToolbar.addWidget(self.startBtn)
        self.btnToolbar.addWidget(self.stopBtn)

        # Central UI
        self.broswer = QtWidgets.QTextBrowser()
        self.mainLayout.addWidget(self.broswer, 1, 0, 5, 3)

        # Botton UI
        self.bottomLayout = QtWidgets.QHBoxLayout()
        self.label1 = QtWidgets.QLabel("placeholder")
        self.bottomLayout.addWidget(self.label1)
        self.mainLayout.addLayout(self.bottomLayout, 6, 0, 1, 3)

    def init_args(self):
        pass

    def init_slots(self):
        self.aboutAction.triggered.connect(self.show_about_action)
        self.saveConfigAction.triggered.connect(self.save_config_action)
        self.loadConfigAction.triggered.connect(self.load_config_action)

    def show_about_action(self):
        aboutActionDialog = AboutDialog(self.lang)
        aboutActionDialog.exec_()

    def save_config_action(self):
        config_file_name, ok = QFileDialog.getSaveFileName(None, "文件保存到", tools.CONFIG_FILE)
        if ok:
            logging.info("Save current configuration to: " + config_file_name)
            if config_file_name[-5:] != '.yaml':
                config_file_name = config_file_name + '.yaml'
            res = tools.generate_yaml_doc(config_file_name, self.configs)
            if type(res) != 'int':
                tools.show_dialog(self.ui_main.mainwindow, "保存成功：" + res, tools.INFO)
            else:
                tools.show_dialog(self.ui_main.mainwindow, "保存失败：" + str(res), tools.ERROR)
            logging.info("Save configuration result: " + str(res))
        else:
            logging.info("User canceled save configuration action.")

    def load_config_action(self):
        config_file_name, ok = QFileDialog.getOpenFileName(None, "选择文件", tools.CONFIG_FILE,
                                                           "yaml file(*.yaml);;yml file(*.yml)")
        if ok:
            logging.info("User select load configuration: " + config_file_name)
            self.configs = tools.load_yaml(config_file_name)
        else:
            logging.info("User canceled load configuration action.")


if __name__ == '__main__':
    basic_log_config()
    app = QtWidgets.QApplication(sys.argv)
    app_name = load_yaml(tools.CONFIG_FILE)["APP"]["APP_NAME"]
    try:
        socket = QLocalSocket()
        socket.connectToServer(app_name)
        if socket.waitForConnected(500):
            tools.message_box("错误", "该程序正在运行中！")
            app.quit()
        else:
            local_server = QLocalServer()
            local_server.listen(app_name)
            main_window = MainFrame()
            main_window.show()
            sys.exit(app.exec_())
    except Exception as e:
        tools.message_box("错误", "启动失败： " + str(e))
